/* 
 * Jquery插件
 * @since 1.0 2014-7-16 by sutroon
 */

/**
 * 时间选择插件
 * @param {jQuery} $
 * @returns {void}
 * @since 1.0 2014-7-16 by sutroon
 * @example
 * &lt;input type="text" name="beginTime" class="timepicker" value="9:30" /&gt;
 * $('.timepicker').timepicker();
 */
(function ($) {
    $.fn.timepicker = function (options) {
        var opts = $.extend({}, $.fn.timepicker.defaults, options);
        var timp_strH = '';
        var timp_strM = '';
        var timp_strS = '';
        var timp_strT = '';
        var strI;
        for (var i = 0; i < 60; i++) {
            strI = (opts.padding && i < 10) ? '0' + i : i;
            timp_strT = '<option value="' + strI + '">' + strI + '</option>';
            if (i < 24) {
                timp_strH += timp_strT;
            }
            timp_strM += timp_strT;
            timp_strS += timp_strT;
        }
        timp_strT = '';
        if (opts.showHour) {
            timp_strT += '<select name="{0}_H">' + timp_strH + '</select>时';
        }
        if (opts.showMinute) {
            timp_strT += '<select name="{0}_M">' + timp_strM + '</select>分';
        }
        if (opts.showSecond) {
            timp_strT += '<select name="{0}_S">' + timp_strS + '</select>秒';
        }
        return this.each(function () {
            var $this = $(this);
            var name = $this.attr('name');
            var value = $this.val();
            if (!value && opts.initValue) {
                value = opts.initValue;
            }
            var arrVal = value.split(':');
            var required = $this.prop('required') ? ' required' : '';
            var $str = $('<span><input type="hidden" name="' + name + '" value="' + value + '" />' + timp_strT.replace(/\{0\}/g, name) + '</span>');
            if (required) {
                $str.find('select').prop('required', true);
            }
            if (opts.showHour) {
                $str.find('select[name="' + name + '_H"]').find('option[value="' + arrVal[0] + '"]').prop('selected', true);
            }
            if (opts.showMinute && arrVal.length > 1) {
                $str.find('select[name="' + name + '_M"]').find('option[value="' + arrVal[1] + '"]').prop('selected', true);
            }
            if (opts.showSecond && arrVal.length > 2) {
                $str.find('select[name="' + name + '_S"]').find('option[value="' + arrVal[2] + '"]').prop('selected', true);
            }
            $str.find('select').change(function () {
                var val = '';
                $str.find('select').each(function (i, o) {
                    val += $(o).val() + ':';
                })
                $str.find('input').val(val.substring(0, val.length - 1));
            });
            $this.replaceWith($str);
        });
    };
    $.fn.timepicker.defaults = {
        showHour: true,
        showMinute: true,
        showSecond: true,
        initValue: '00:00:00', // 初始的默认值
        padding: true // 是否补齐两位数
    };
})(jQuery);


/**
 * 音频播放器插件
 * .audio-player标签必需加2个属性：data-src和title,其中,title内容为文件名,如果文件名为空则不渲染.
 * @param {jQuery} $
 * @returns {void}
 * @since 1.0 2014-7-22 by sutroon
 * @example
 *        <td><span class="audio-player" data-src="{:get_voc_url('sounds')}{$vo.dirName}/{$vo.music}" title="{$vo.music}"><a href="?s=VoiceMenu/item_edit/id/{$vo.id}.html">[编辑]</a><a href="#" onclick="JQUIHelper.confirm_redirect('?s=VoiceMenu/item_delete/id/{$vo.id}.html')">[删除]</a></span></td>
 */
(function ($) {
    $.fn.audioPlayer = function (options) {
        var opts = $.extend({}, $.fn.audioPlayer.defaults, options);
        return this.each(function () {
            var $this = $(this);
            var title = $this.attr('title');
            if (title) {
                var src = $this.data('src');
                var links = $this.html();
                var linkscount = $this.find('a').length;
                var str = '<div class="soplayer' + (linkscount > 0 ? ' lnkx' + linkscount : '') + '"><span class="playermask"><audio src="' + src + '" controls="controls">您的浏览器不支持播放器插件,请升级到IE10以上的浏览器版本或火狐、谷歌等现代浏览器</audio></span>' + links + '<i style="clearfix"></i></div>';
                $this.parent().addClass('tdplayer').attr('title', title).html(str);
            } else {
                if (opts.allowEmpty) {
                    $this.parent().html('');
                }
            }
        });
    };
    $.fn.audioPlayer.defaults = {allowEmpty: true};
})(jQuery);

/**
 * 设置文件域
 * @param {jQuery} $
 * @returns {void}
 * @since 1.0 2014-7-28 by sutroon
 * @example
 *        <input type="hidden" class="uploader" value="/upload/abc.jpg" />
 *        $('.uploader').setFileInput();
 */
(function ($) {
    $.fn.setFileInput = function (options) {
        var opts = $.extend({}, $.fn.setFileInput.defaults, options);
        return this.each(function () {
            var $this = $(this);
            var val = $this.val();
            var str = '<input type="file" name="' + $this.attr('name') + '" />';
            if (val.indexOf('.') > -1) {
                var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase();
                var fileName = val;
                if (val.indexOf('/') > -1) {
                    fileName = fileName.substring(val.lastIndexOf('/') + 1);
                }
                $this.removeAttr('data-value');
                if ('.jpg.jpeg.png.gif.'.indexOf('.' + ext + '.') > -1) {
                    str = '<a href="' + val + '" target="_blank"><img src="' + val + '" alt="" style="width:' + opts.imgWidth + 'px; height:' + opts.imgHeight + 'px;" /></a> ' + str;
                } else {
                    str = '<a href="' + val + '" target="_blank">[' + fileName + ']</a> ' + str;
                }
            }
            $this.replaceWith(str);
        });
    };
    $.fn.setFileInput.defaults = {imgWidth: 60, imgHeight: 60};
})(jQuery);

/**
 * 将表格格式化为树形列表
 * @param {jQuery} $
 * @returns {void}
 * @since 1.0 2014-8-21 by sutroon
 * @example $('.table-tree').tableTree();
 */
(function ($) {
    $.fn.tableTree = function (options) {
        var opts = $.extend({}, $.fn.tableTree.defaults, options);
        return this.each(function () {
            var $this = $(this);
            $this.find('tr').each(function () {
                var $tr = $(this);
                var $trn = $tr.next();
                var lvl = $tr.data('level');
                var pad = '';
                var $td = $tr.find('td:first-child');
                var tog = '';
                if ($td[0]) {
                    if ($trn[0]) {
                        var lvln = $trn.data('level');
                        if (lvln !== undefined && lvln > lvl) {
                            tog = ' <a href="#" onclick="return $.fn.sotoggle(this);">[-]</a>';
                        }
                    }
                    if (lvl !== undefined) {
                        lvl = lvl * 2;
                        while (lvl > 0) {
                            pad += opts.padChar;
                            lvl--;
                        }
                    }
                    $td.html(opts.padWrap.replace('{0}', pad) + $td.html() + tog);
                }
            })
        });
    };
    $.fn.sotoggle = function (o) {
        var $a = $(o);
        var $tr = $a.parent().parent();
        var lvl = $tr.data('level');
        var txt = $a.text();
        $tr.nextAll().each(function () {
            var $tr2 = $(this);
            var lvl2 = $tr2.data('level');
            if (lvl2 == undefined || lvl2 <= lvl) {
                return;
            }
            if (txt == '[-]') {
                $tr2.hide();
            } else {
                $tr2.show();
            }
        });
        $a.text(txt == '[-]' ? '[+]' : '[-]');
        return false;
    };
    $.fn.tableTree.defaults = {padChar: '..', padWrap: '<span style="color:#CCC;">{0}</span>'};
})(jQuery);

/**
 * 消息对话框
 * @since 1.0 2014-9-19 by sutroon
 * @example $.somessager.alert('提示','删除失败');
 */
(function ($) {
    $.extend({
        'somessager': {
            /**
             * 弹出消息提示框
             * @param msg
             * @param caption
             * @since 1.0 2014-9-18 by sutroon
             * @example $.somessager.alert('提示','请选中一行');
             */
            'alert': function (title, msg) {
                $('<div title="' + (title ? title : '消息') + '">' + msg + '</div>').dialog({
                    buttons: {
                        '确定': function () {
                            $(this).dialog('close');
                        }
                    }
                });
            }
        }
    });
})(jQuery);

/**
 * 进度条单元格
 * @since 1.0 2014-9-26 by sutroon; 2014-9-27 by sutroon 修正百分比超过100时td溢出的问题
 * @example $('.tdProgressbar').tdProgressbar();
 */
(function ($) {
    $.fn.tdProgressbar = function (options) {
        var opts = $.extend({}, $.fn.tdProgressbar.defaults, options);
        return this.each(function () {
            var $this = $(this);
            var txt = $this.text();
            if (txt.indexOf('%') > -1) {
                txt = txt.replace('%', '');
            }
            if (txt.length == 0) {
                txt = 0;
            }
            $this.html('<div class="' + opts.borderClass + '"><div class="' + opts.bgClass + '" style="width:' + (txt > 100 ? 100 : txt) + '%">' + txt + '%</div></div>');
        });
    };
    $.fn.tdProgressbar.defaults = {borderClass: 'bor', bgClass: 'bg', infoClass: 'info'};
})(jQuery);

/**
 * 滚动插件
 * @since 1.0 2014-10-6 by sutroon
 * @example
 *  <div class="notices-panel"><p>这里是滚动的图片或文字</p><p>这里是滚动的图片或文字</p><p>这里是滚动的图片或文字</p><p>这里是滚动的图片或文字</p><p>这里是滚动的图片或文字</p></div>
 *  $('.notices-panel').marqueeLeft({speed: 40, width: '600px', hide: true});
 *  .notices-panel { color: #FFF; margin: 5px 0px 0px 25px; }
.notices-panel table, .notices-panel td, .notices-panel th { border: none; padding: 0px; margin: 0px; white-space: nowrap; }
.notices-panel td { padding: 0px 10px; }
.notices-panel a { color: #FFF; }
 */
(function ($) {
    $.fn.marqueeLeft = function (options) {
        var opts = $.extend({}, {speed: 30, width: '410px', height: '16px', splitor: 'p', hide: false}, options);
        return this.each(function () {
            var $this = $(this);
            if (opts.hide) {
                $this.hide();
            } else {
                $this.find(opts.splitor).wrap('<td></td>');
                $this.wrapInner('<table cellpadding="2" cellspacing="0" border="0"><tr align="center"></tr></table>');
                $this.css({'overflow': 'hidden', 'height': opts.height, 'width': opts.width, 'white-space': 'nowrap'});
                var contents = $this.html();
                $this.html('<table cellpadding="0" cellspacing="0" border="0"><tr><td class="col1" valign="top" align="center">' + contents + '</div> </td><td class="col2" valign="top"></td></tr></table>');
                var col2 = $this.find('.col2')[0];
                var col1 = $this.find(".col1")[0];
                var col = $this[0];
                col2.innerHTML = col1.innerHTML; //克隆colee1为colee2
                var diff=0;
                function Marquee() {
                    if (col2.offsetWidth - col.scrollLeft <= 0)//offsetWidth 是对象的可见宽度
                        col.scrollLeft -= col1.offsetWidth//scrollWidth 是对象的实际内容的宽，不包边线宽度
                    else {
                        diff=col.scrollLeft;
                        col.scrollLeft++
                        if(diff==col.scrollLeft){
                            col.scrollLeft -= col1.offsetWidth;
                        }
                    }
                }

                var MyMar = setInterval(Marquee, opts.speed);
                col.onmouseover = function () {
                    clearInterval(MyMar)
                }
                col.onmouseout = function () {
                    MyMar = setInterval(Marquee, opts.speed)
                }
            }
        })
    };
})(jQuery);

/**
 * ul树形列表
 * @since 1.0 2014-10-28 by sutroon
 * @example <ul class="ul-tree"><li><span>[-]</span><input type="checkbox" name="ids[]" value="1" checked="checked" /><strong>系统管理</strong><ul><li><span>[-]</span><input type="checkbox" name="ids[]" value="2" checked="checked" /><strong>系统管理</strong><ul><li><input type="checkbox" name="ids[]" value="3" /><strong>操作员管理</strong></li><li><input type="checkbox" name="ids[]" value="4" /><strong>费率管理</strong></li></ul></li></ul></li></ul>
 * $('.ul-tree').ulTree();
 */
(function ($) {
    $.fn.ulTree = function () {
        return this.each(function () {
            var $this = $(this);
            $this.find('li ul').parent().before('<span>[-]</span>');

            /**
             * 树形菜单展开收起
             * @since 1.0 2014-10-7 by sutroon
             */
            $this.find('span').click(function () {
                var $this = $(this);
                if ($this.text() == '[-]') {
                    $this.parent().find('ul').hide();
                    $this.text('[+]');
                } else {
                    $this.parent().find('ul').show();
                    $this.text('[-]');
                }
            })

            /**
             * 树形菜单选项框选中
             * @since 1.0 2014-10-7 by sutroon
             */
            $this.find('input:checkbox').change(function () {
                var $this = $(this);
                var n = $this.parent().siblings().children('input:checked').length;
                if ($this.prop('checked') == false && n > 0) {
                    return;
                }
                $this.parents('li').children('input:checkbox').prop('checked', $this.prop('checked'));
            })
        });
    }
})(jQuery);

/**
 * 中国省市区插件
 * @param {type} $
 * @returns {undefined}
 * @since 1.0 2014-12-11 by sutroon
 * @remark 搞了1个工作日,总算完成了一个心头大事!
 * @example
 *  <input type="text" name="address" />
 *  <div id="region1"><select name="province"></select><select name="city"></select><select name="area"></select></div>
 *  <div id="region2"><select name="province"></select><select name="city"></select><select name="area"></select></div>
 *  <select name="province1"></select><select name="city1"></select><select name="area1"></select>     * 
 *  $(function () {
 *      $.cnRegion({'province': '福建省', 'city': '厦门市', 'area': '思明区', 'names': 'province,city,area', 'container': '#region1', 'changeFunc': ('undefined' == typeof (changeRegion) ? undefined : changeRegion)});
 *      $.cnRegion({'province': '山西省', 'city': '太原市', 'area': '小店区', 'names': 'province,city,area', 'container': '#region2'});
 *      $.cnRegion({'province': '', 'city': '', 'area': '', 'names': 'province1,city1,area1'});
 *  });
 *  function changeRegion(province, city, area) {
 *      $('input[name="address"]').val(province + ' ' + city + ' ' + area);
 *  }     
 */
(function ($) {
    $.extend({
        'cnRegion': function (options) {
            var opts = $.extend({}, {'province': '', 'city': '', 'area': '', 'url': '', 'names': 'province,city,area', 'container': '', 'changeFunc': undefined}, options);
            if (!opts.url) {
                opts.url = $('#hidval_region_api').val();
            }
            var names = opts.names.split(',');
            if (opts.container) {
                opts.container += ' ';
            }
            names[0] = opts.container + 'select[name="' + names[0] + '"]';
            names[1] = opts.container + 'select[name="' + names[1] + '"]';
            names[2] = opts.container + 'select[name="' + names[2] + '"]';
            var $province = $(names[0]);
            var $city = $(names[1]);
            var $area = $(names[2]);
            var defaultoption = '<option value="">请选择</option>';
            $province.html(defaultoption);
            $city.html(defaultoption);
            $area.html(defaultoption);
            $.post(opts.url, function (data) {
                if (typeof (data) == 'string') {
                    return;
                }
                var str = defaultoption;
                for (var i in data) {
                    str += '<option value="' + data[i] + '">' + data[i] + '</option>';
                }
                $province.html(str);
                if (opts.province) {
                    $province.find('option[value="' + opts.province + '"]').prop('selected', 'selected');
                }
            });
            if (opts.province) {
                load_city(opts.province);
            }
            if (opts.city) {
                load_area(opts.province, opts.city);
            }
            $province.change(function () {
                if ($(this).val()) {
                    load_city($(this).val());
                    $area.html(defaultoption);
                } else {
                    $city.html(defaultoption);
                    $area.html(defaultoption);
                }
                if ('function' == typeof (opts.changeFunc)) {
                    opts.changeFunc($(this).val(), '', '');
                }
            });
            $city.change(function () {
                if ($(this).val()) {
                    load_area($(names[0]).val(), $(this).val());
                } else {
                    $area.html(defaultoption);
                }
                if ('function' == typeof (opts.changeFunc)) {
                    opts.changeFunc($(names[0]).val(), $(this).val(), '');
                }
            });
            if ('function' == typeof (opts.changeFunc)) {
                $area.change(function () {
                    opts.changeFunc($(names[0]).val(), $(names[1]).val(), $(this).val());
                })
            }
            function load_city(province) {
                if (!province) {
                    $city.html('<option value="">请选择</option>');
                    return;
                }
                $.post(opts.url, {'province': province}, function (data) {
                    if (typeof (data) === 'string') {
                        return;
                    }
                    var str = defaultoption;
                    for (var i in data) {
                        str += '<option value="' + data[i] + '">' + data[i] + '</option>';
                    }
                    $city.html(str);
                    if (opts.city) {
                        $city.find('option[value="' + opts.city + '"]').prop('selected', 'selected');
                    }
                });
            }
            function load_area(province, city) {
                if (!province) {
                    $area.html('<option value="">请选择</option>');
                    return;
                }
                $.post(opts.url, {'province': province, 'city': city}, function (data) {
                    if (typeof (data) === 'string') {
                        return;
                    }
                    var str = defaultoption;
                    for (var i in data) {
                        str += '<option value="' + data[i] + '">' + data[i] + '</option>';
                    }
                    $area.html(str);
                    if (opts.area) {
                        $area.find('option[value="' + opts.area + '"]').prop('selected', 'selected');
                    }
                });
            }
        }
    });
})(jQuery);

/**
 * 内容分页插件
 * 把内容分页分页
 * @param {jQuery} $
 * @returns {void}
 * @since 1.0 2015-3-12 by sutroon
 * @example
 *        <div class="contentpaging">1234567890一二三四五六七八九十</div>
 *        $('.contentpaging').contentpaging({pagesize:2});
 */
(function ($) {
    $.fn.contentpaging = function (options) {
        var opts = $.extend({}, $.fn.contentpaging.defaults, options);
        return this.each(function () {
            var $this = $(this);
            var content = $this.html();
            if (content) {
                var pagecount = content.length / opts.pagesize;
                if (pagecount > 1) {
                    var pager = '';
                    var newcontent = '';
                    for (var i = 0; i < pagecount; i++) {
                        newcontent += '<div class="' + opts.class + '"' + (i < 1 ? '' : ' style="display:none;"') + '>' + content.substring(i * opts.pagesize, (i + 1) * opts.pagesize) + '</div>';
                        pager += '<a href="#" onclick="$(this).parent().parent().find(\'.' + opts.class + '\').hide().eq(' + i + ').show(); return false;">' + i + '</a> ';
                    }
                    if (opts.istop) {
                        newcontent = '<div class="' + opts.class + 'bar">' + pager + '</div>' + newcontent;
                    } else {
                        newcontent += '<div class="' + opts.class + 'bar">' + pager + '</div>';
                    }
                    $this.html(newcontent);
                }
            }
        });
    };
    $.fn.contentpaging.defaults = {pagesize: 30, class: 'cntpaging', istop: false};
})(jQuery);